//
//  ReportConfig.swift
//  ANOA
//
//  Created by zwb on 2016/12/12.
//  Copyright © 2025 aowang. All rights reserved.
//

import UIKit
let ReportListPlistPath = "ReportList.plist"
/// 全部报表
var AllReportList = [Report]()
class ReportConfig: NSObject {

    static let sharedInstance = ReportConfig()

    fileprivate override init() {} // 防止初始化

    func fetchReport() {

        let version = ReportHelper.shared.reportVersion().unwrap

        KSNetwork.shared.fetchReport(API.queryReport(version: version), successHandle: { [weak self] data in
            
            guard let `self` = self else {
                return
            }


            DispatchQueue.global().async {

                let mapped = JSON(data)

            
                let reportObject = ReportInfos(json: mapped)

                let documentDirectoryURL = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first

                let fileURL = documentDirectoryURL!.appendingPathComponent(ReportListPlistPath)
 
                if reportObject.flag == TRUE {

                    let reportDictionary = reportObject.dictionaryRepresentation()

                    // 将获取到新的报表配置表存入本地
                    if NSKeyedArchiver.archiveRootObject(reportDictionary, toFile: fileURL.path) {
                        KSLog(TRUE)
                    }

                    ReportHelper.shared.setReportVersion(reportObject.versionNo.unwrap)

                    // 区分通用报表和排行榜报表

                    if let info = reportObject.infos {
                        
                        DyReportTool.shared.sortChart(info)

                    }

                } else { // 网络获取失败就从本地获取报表
                    self.fetchReportFromLocal()
                }

                DispatchQueue.main.async(execute: {
                    NotificationCenter.default.post(name: Notification.Name.Grpt.reportList, object: nil)
                })
            }
  
            }, errorHandle: {
        
            self.fetchReportFromLocal()
        })
    }

    fileprivate func fetchReportFromLocal() {

        let documentDirectoryURL = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first

        let fileURL = documentDirectoryURL!.appendingPathComponent(ReportListPlistPath)

        if let loadReportList = NSKeyedUnarchiver.unarchiveObject(withFile: fileURL.path) as? [String: Any] {

            let loadReportList = loadReportList["infos"] as? NSArray

            guard loadReportList != nil else { return }

            var reports = [Report]()

            // 从本地plist获取配置表
            for item in loadReportList! {
                let reportParameter = Report(object: item)
                reports.append(reportParameter)
            }

            DyReportTool.shared.sortChart(reports)
        }
    }


   

// 装配参数
    func assemblyParameters(_ report: Report) -> [String: String] {
        var parameters = [String: String]()
        // 插入两个必备参数
        parameters.updateValue("oam", forKey: "cached")
        parameters.updateValue(TOKEN, forKey: "session")

        guard let detail = report.details else { return ["": ""] }

        for item in detail {

            if item.defaultVal != "" {

                let postChar = item.sPostChar.unwrap
                let sPrefixChar = item.sPrefixChar.unwrap
                var defaultVal = item.defaultVal.unwrap

                var value = sPrefixChar + defaultVal + postChar

                parameters.updateValue(value, forKey: item.titleNm!)

                if item.typeCs == "4" { // 月份
                    if defaultVal == "1" {
                        defaultVal = Date.currentMonth
                    } else if defaultVal == "2" {
                        defaultVal = getPrevYearAndMonth(1)
                    } else if defaultVal == "3" {
                        if let n = item.sRemarks {
                            defaultVal = getPrevYearAndMonth(Int(n) ?? 1)
                        } else {
                            defaultVal = getPrevYearAndMonth(1)
                        }
                    }

                    value = sPrefixChar + defaultVal + postChar
                    parameters.updateValue(value, forKey: item.titleNm!)

                } else if item.typeCs == "5" {

                    if defaultVal == "1" {
                        defaultVal = Date.today
                    } else if defaultVal == "2" {
                        defaultVal = Date.firstDateOfMonth
                    } else if defaultVal == "3" {
                        if let n = item.sRemarks {
                            defaultVal = getPrevDay(Double(n) ?? 1.0)
                        } else {
                            defaultVal = getPrevDay(1.0)
                        }
                    }

                    value = sPrefixChar + defaultVal + postChar
                    parameters.updateValue(value, forKey: item.titleNm!)

                } else if item.ifSession == "1" {

                    if defaultVal == "org_code" || defaultVal == "org_name" {
                        let value = sPrefixChar + USERINFO.cUnitnameIdHs! + postChar
                        parameters.updateValue(value, forKey: item.titleNm!)
                    } else {
                        if let valuex = USERINFO.dictionaryRepresentation()[defaultVal] as? String {
                            let value = sPrefixChar + valuex + postChar
                            parameters.updateValue(value, forKey: item.titleNm!)
                        } else {
                            parameters.updateValue("[未识别配置]", forKey: item.titleNm!)
                        }
 
                    }
                }
            }
        }

        return parameters
    }
}
// 跳转到报表参数展示界面
func pushReportViewController(oneReport: [Report],controller:UIViewController) {
    
    let reVC = UIStoryboard(name: "Report", bundle: Bundle.main).instantiateViewController(withIdentifier: "ReportViewController") as! ReportViewController
    reVC.reportParameters = oneReport
    
    func pushController() {
        if oneReport.count == 1 {
            
            let reportPara = oneReport.first!
            let num = reportPara.details.map { $0.filter { $0.ifShow == "1" } }
            if num?.count == 0 {
                let para = ReportConfig.sharedInstance.assemblyParameters(reportPara)
                
                go2ChartForWeb_OA(url: BaseReportUrl, path: reportPara.reportUrl!, title: reportPara.reportName ?? "标题", parameters: para, currentVC: controller)
                
            } else {
                controller.navigationController?.pushViewController(reVC, animated: true)
            }
        } else {
            controller.navigationController?.pushViewController(reVC, animated: true)
        }
        
    }
    
    let SMSValidKey = "\(USERINFO.staffId!)isSmsValid"
    
    if oneReport.first!.isLock == "1" {
        let vc = GesturePasswordViewController()
        vc.goNextVC = { (  flag) in
            
            if flag == true {
                
                
                if oneReport.first!.isSmsValid == "1" {
                    
                    let isSmsValid = UserDefaults.standard.object(forKey: SMSValidKey) as? String
                    // 今天通过了短信验证后了就不在进行验证
                    if let sms = isSmsValid {
                        if sms != Date.today {
                            
                            go2SmsVeri(sms_type: "1") {
                                pushController()
                            }
                            
                        } else {
                            pushController()
                        }
                    } else {
                        
                        go2SmsVeri(sms_type: "1") {
                            pushController()
                        }
                        
                    }
                } else {
                    pushController()
                }
                
            }
        }
        
        controller.present_FullScreen(to: vc)
    } else {
        if oneReport.first!.isSmsValid == "1" {
            
            let isSmsValid = UserDefaults.standard.object(forKey: SMSValidKey) as? String
            // 今天通过了短信验证后了就不在进行验证
            if let sms = isSmsValid {
                if sms != Date.today {
                    
                    go2SmsVeri(sms_type: "1") {
                        pushController()
                    }
                } else {
                    pushController()
                }
            } else {
                go2SmsVeri(sms_type: "1") {
                    pushController()
                }
            }
        } else {
            pushController()
        }
    }
    
    
    
}
